import * as XLSX from 'xlsx'
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

const useExportFile = () => {
    // 导出excel
    const dataToExcel = <T>(data: T[], fileName: string, header: Array<string>) => {
        // 创建一个工作簿
        const workbook = XLSX.utils.book_new();
        const ws = XLSX.utils.json_to_sheet([], { header, skipHeader: false });
        const worksheet = XLSX.utils.sheet_add_json(ws, data, { origin: 'A2', skipHeader: true });
        // 将工作表添加到工作簿中
        XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
        // 导出Excel文件
        XLSX.writeFile(workbook, fileName + '.xlsx');
    }
    // 导出PDF
    const exportPDF = (domId: string, fileName: string) => {
        const input = document.getElementById(domId); // 获取要转换的DOM元素ID
        html2canvas(input as HTMLElement).then(canvas => {
            const imgData = canvas.toDataURL('image/png'); // 将Canvas转换为图片格式
            const pdf = new jsPDF(); // 创建新的PDF文档实例
            (pdf as { addImage: any }).addImage(imgData, 'PNG', 0, 0); // 将图片添加到PDF中，位置为(0,0)
            pdf.save(`${fileName}.pdf`); // 保存PDF文件，并提供文件名
        });
    }
    return { dataToExcel, exportPDF }
}

export default useExportFile;